package com.zhongshengnetwork.rightbe.lang.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
//import android.support.v4.app.FragmentActivity;
//import android.support.v4.content.ContextCompat;
//import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.zhongshengnetwork.rightbe.clerk.view.ClerkFragment;
import com.zhongshengnetwork.rightbe.clerk.view.ClerkRecyclerFragment;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.FragmentViewPageAdapter;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.gsonmodel.CareStateModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.UserInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.view.CommentFragment;
import com.zhongshengnetwork.rightbe.lang.view.HonorLangFragment;
import com.zhongshengnetwork.rightbe.lang.view.UserFragment;
import com.zhongshengnetwork.rightbe.lang.view.UserLangFragment;
import com.zhongshengnetwork.rightbe.lang.view.UserLifeLangFragment;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.WZTFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserLangActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener,View.OnClickListener{//BaseFragmentActivity

    private TopBarView topbar;
    private TextView text1, text2, text3, text4, text5, text6;
    private ImageView tabLine;
    private ViewPager pager;
    private DisplayMetrics dm = new DisplayMetrics();
    private int tabWidth;
    private List<Fragment> fragments;
    private String userid;
    private int type = 0;
    private boolean isCare = false;
    private String title;
    private UserLangFragment userLangFragment;
    private CommentFragment  commentFragment;
    //private ClerkRecyclerFragment clerkRecyclerFragment;
    private ClerkFragment clerkFragment;
    private WZTFragment wztFragment;
    private UserLifeLangFragment userLifeLangFragment;
    private HonorLangFragment honorLangFragment;
    private UserFragment userFragment;
    //图片浏览
    public ImageViewer imagePreivew;
    //加载动画
    private AVLoadingIndicatorView avi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_lang);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.getRightTextView().setTextSize(15);
        topbar.setClickListener(this);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickCare();
            }
        });
        imagePreivew = (ImageViewer) findViewById(R.id.imagePreivew);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        type = getIntent().getIntExtra(APIKey.typeKey,0);
        title = getIntent().getStringExtra(APIKey.titleKey);
        if (!CommonUtils.isEmpty(title)){
            topbar.getTitleView().setText(title);
        }
        topbar.getTitleView().setClickable(true);
        topbar.getTitleView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fragments != null && fragments.size() > 0){
                    if (pager.getCurrentItem() == 1){
                        userLangFragment.getFirstData(true);
                    }else if (pager.getCurrentItem() == 2){
                        userLifeLangFragment.getFirstData(true);
                    }
                }
            }
        });
        userid = getIntent().getStringExtra(APIKey.useridKey);
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        tabWidth = dm.widthPixels / 6;
        fragments = new ArrayList<Fragment>();
        initView();
        if (!CommonUtils.isEmpty(userid) && userid.equals(APIKey.noname_userid) == false){
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    getCareState();
                }
            }.start();
        }

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    //点击了关注
    private void onClickCare(){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(UserLangActivity.this,LoginActivity.class);
            startActivity(intent);
            return;
        }
        if (isCare == true){
            CustomDialog dialog = null;
            final CustomDialog.Builder builder = new CustomDialog.Builder(UserLangActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("确定要取消关注？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    dealWithCare(false);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog = builder.create();
            dialog.show();
        }else {
            dealWithCare(true);
        }
    }

    private void initView() {
        text1 = (TextView) findViewById(R.id.text1);
        text1.setOnClickListener(this);
        text2 = (TextView) findViewById(R.id.text2);
        text2.setOnClickListener(this);
        text3 = (TextView) findViewById(R.id.text3);
        text3.setOnClickListener(this);
        text4 = (TextView) findViewById(R.id.text4);
        text4.setOnClickListener(this);
        text5 = (TextView) findViewById(R.id.text5);
        text5.setOnClickListener(this);
        text6 = (TextView) findViewById(R.id.text6);
        text6.setOnClickListener(this);

        text1.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text2.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text3.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text4.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text5.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text6.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        tabLine = (ImageView) findViewById(R.id.tabLine);
        pager = (ViewPager) findViewById(R.id.pager);

        userFragment = new UserFragment();
        userFragment.userid = CommonUtils.formatString(userid);
        fragments.add(userFragment);
        userLangFragment = new UserLangFragment();
        userLangFragment.userid = CommonUtils.formatString(userid);
        userLangFragment.userLangActivity = UserLangActivity.this;
        userLangFragment.mainActivity = null;
        fragments.add(userLangFragment);

        /*
        clerkRecyclerFragment = new ClerkRecyclerFragment();
        fragments.add(clerkRecyclerFragment);
        */
        clerkFragment = new ClerkFragment();
        clerkFragment.dataType = 2;
        clerkFragment.userId = userid;
        fragments.add(clerkFragment);

        wztFragment = new WZTFragment();
        wztFragment.userid =userid;
        fragments.add(wztFragment);
        /*
        commentFragment = new CommentFragment();
        commentFragment.type = 0;
        commentFragment.userid = userid;
        fragments.add(commentFragment);
        */
        userLifeLangFragment = new UserLifeLangFragment();
        userLifeLangFragment.userid = CommonUtils.formatString(userid);
        userLifeLangFragment.userLangActivity = UserLangActivity.this;
        userLifeLangFragment.mainActivity = null;
        fragments.add(userLifeLangFragment);

        honorLangFragment = new HonorLangFragment();
        honorLangFragment.userid = CommonUtils.formatString(userid);
        fragments.add(honorLangFragment);

        /**
         * 这里Activity 只有继承 FragmentActivity 的时候 ，才会 getSupportFragmentManager()
         */
        // 设置适配器
        FragmentViewPageAdapter fragmentViewPageAdapter = new FragmentViewPageAdapter(
                getSupportFragmentManager(), fragments);
        pager.setAdapter(fragmentViewPageAdapter);
        pager.setOnPageChangeListener(new PageListener());

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.tab_line);
        int w = tabWidth;
        if (bitmap.getWidth()<tabWidth){
            w = bitmap.getWidth();
        }
        int h = 8;
        if (bitmap.getHeight() < h){
            h = bitmap.getHeight();
        }
        Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, w, h);// 设置tab的宽度和高度
        tabLine.setImageBitmap(b);

        RelativeLayout activity_user_layout = (RelativeLayout) findViewById(R.id.activity_user_layout);
        activity_user_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text1:
                pager.setCurrentItem(0);
                break;
            case R.id.text2:
                pager.setCurrentItem(1);
                break;
            case R.id.text3:
                pager.setCurrentItem(2);
                break;
            case R.id.text4:
                pager.setCurrentItem(3);
                break;
            case R.id.text5:
                pager.setCurrentItem(4);
                break;
            case R.id.text6:
                pager.setCurrentItem(5);
                break;
            default:
                break;
        }
    }

    /**
     * 监听
     */
    public class PageListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            Matrix matrix = new Matrix();
            // 设置激活条的最终位置
            switch (arg0) {
                case 0:
                    // 使用set直接设置到那个位置
                    matrix.setTranslate(0, 0);
                    break;
                case 1:
                    matrix.setTranslate(tabWidth, 0);
                    break;
                case 2:
                    matrix.setTranslate(tabWidth*2, 0);
                    break;
                case 3:
                    matrix.setTranslate(tabWidth*3, 0);
                    break;
                case 4:
                    matrix.setTranslate(tabWidth*4, 0);
                    break;
                case 5:
                    matrix.setTranslate(tabWidth*5, 0);
                    break;
            }
            // 在滑动的过程中，计算出激活条应该要滑动的距离
            float t = (tabWidth) * arg1;
            // 使用post追加数值
            matrix.postTranslate(t, 0);
            tabLine.setImageMatrix(matrix);
        }

        @Override
        public void onPageSelected(int arg0) {
            text1.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            text2.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            text3.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            text4.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            text5.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            text6.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            switch (arg0) {
                case 0:
                    text1.setTextColor(Color.parseColor("#ff008000"));
                    break;
                case 1:
                    text2.setTextColor(Color.parseColor("#ff008000"));
                    break;
                case 2:
                    text3.setTextColor(Color.parseColor("#ff008000"));
                    break;
                case 3:
                    text4.setTextColor(Color.parseColor("#ff008000"));
                    break;
                case 4:
                    text5.setTextColor(Color.parseColor("#ff008000"));
                    break;
                case 5:
                    text6.setTextColor(Color.parseColor("#ff008000"));
                    break;
                default:
                    break;
            }
        }
    }

    //获取关注状态
    private void getCareState(){
        Log.e("TAG","获取关注状态");
        if (CommonUtils.isLogin() == false){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    topbar.getRightTextView().setText("+ 关注");
                    topbar.getRightTextView().setTextColor(Color.parseColor("#FFFFFF"));
                    topbar.getRightTextView().setVisibility(View.VISIBLE);
                }
            });
            return;
        }else {
            if (userid.equals(CustomApplication.loginModel.getUid())){//自己除外
                topbar.getRightTextView().setVisibility(View.INVISIBLE);
                return;
            }
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("authorid", userid);
            String url = "miniapp/"+"langappid"+"/getcarestate.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    Log.e("TAG","关注结果："+data);
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        final CareStateModel careStateModel = GsonTools.getCareStateModel(data);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("TAG","关注状态："+careStateModel.getIscare());
                                if (careStateModel.getIscare().equals("1")){
                                    topbar.getRightTextView().setText("已关注");
                                    topbar.getRightTextView().setTextColor(Color.parseColor("#909090"));
                                    topbar.getRightTextView().setVisibility(View.VISIBLE);
                                }else {
                                    topbar.getRightTextView().setText("+ 关注");
                                    topbar.getRightTextView().setTextColor(Color.parseColor("#FFFFFF"));
                                    topbar.getRightTextView().setVisibility(View.VISIBLE);
                                }
                            }
                        });
                    }else {
                        CustomApplication.showTip(commonModel, UserLangActivity.this);
                    }
                }

                @Override
                public void onError(String msg) {
                }
            });
        }

        if (CommonUtils.isEmpty(title)){
            final Map<String,String> map = new HashMap<String, String>();
            map.put(APIKey.useridKey,userid);
            map.put(APIKey.tokenKey,CommonUtils.formatString(CustomApplication.loginModel.getToken()));
            HttpsUtils.getUserInfoDo(map, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        final UserInfoModel userInfoModel = GsonTools.getUserInfoModel(data);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                topbar.getTitleView().setText(userInfoModel.getNickname());
                            }
                        });
                    }
                }

                @Override
                public void onError(String msg) {
                    avi.hide();
                }
            });
        }


    }

    //处理关注
    private void dealWithCare(boolean isNeedCare){
        if (userid.equals(CustomApplication.loginModel.getUid())){//自己除外
            topbar.getRightTextView().setVisibility(View.INVISIBLE);
            return;
        }
        if (isNeedCare == true){
            //添加关注
            avi.show();
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("authorid", userid);
            String url = "miniapp/"+"langappid"+"/addcare.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    avi.hide();
                    Log.e("TAG","收藏结果："+data);
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        isCare = true;
                        topbar.getRightTextView().setText("已关注");
                        topbar.getRightTextView().setTextColor(Color.parseColor("#909090"));
                        topbar.getRightTextView().setVisibility(View.VISIBLE);
                    }else {
                        CustomApplication.showTip(commonModel, UserLangActivity.this);
                    }
                }

                @Override
                public void onError(String msg) {
                    avi.hide();
                }
            });
        }else {
            //取消关注
            avi.show();
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("authorid", userid);
            String url = "miniapp/"+"langappid"+"/deletecare.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    avi.hide();
                    Log.e("TAG","收藏结果："+data);
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        isCare = false;
                        topbar.getRightTextView().setText("+ 关注");
                        topbar.getRightTextView().setTextColor(Color.parseColor("#FFFFFF"));
                        topbar.getRightTextView().setVisibility(View.VISIBLE);
                    }else {
                        CustomApplication.showTip(commonModel, UserLangActivity.this);
                    }
                }

                @Override
                public void onError(String msg) {
                    avi.hide();
                }
            });
        }
    }

}
